#include "ThumbnailProxyModel.h"
#include "picturemodel.h"

const unsigned int THUMBNAILE_SIZE = 350;

ThumbnailProxyModel::ThumbnailProxyModel(QObject *parent):
    QIdentityProxyModel (parent)
{
}

QVariant ThumbnailProxyModel::data(const QModelIndex &index, int role) const
{
    if(role != Qt::DecorationRole) {
        return QIdentityProxyModel::data(index, role);
    }
    QString filePath = sourceModel()->data(index, PictureModel::FilePathRole).toString();
    return *mThumbnails[filePath];
}

void ThumbnailProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
{
    QIdentityProxyModel::setSourceModel(sourceModel);
    if(!sourceModel) {
        return;
    }

    connect(sourceModel, &QAbstractItemModel::modelReset, [this] {
        reloadThumbnails();
    });
    connect(sourceModel, &QAbstractItemModel::rowsInserted, [this](const QModelIndex&, int first, int last) {
       generateThumbnails(index(first, 0), last-first+1);
    });
}

PictureModel *ThumbnailProxyModel::pictureModel() const
{
    return static_cast<PictureModel*>(sourceModel());
}

void ThumbnailProxyModel::generateThumbnails(const QModelIndex &startIndex, int count)
{
    if(!startIndex.isValid()) {
        return;
    }

    const QAbstractItemModel* model = startIndex.model();
    int lastIndex = startIndex.row() + count;
    for( int row = startIndex.row(); row < lastIndex; ++row ) {
        QString filePath = model->data(model->index(row, 0), PictureModel::FilePathRole).toString();
        QPixmap pixmap(filePath);
        auto thumbnail = new QPixmap(pixmap.scaled(
                                         THUMBNAILE_SIZE,
                                         THUMBNAILE_SIZE,
                                         Qt::KeepAspectRatio,
                                         Qt::SmoothTransformation));
        mThumbnails.insert(filePath, thumbnail);
    }
}

void ThumbnailProxyModel::reloadThumbnails()
{
    qDeleteAll(mThumbnails);
    mThumbnails.clear();
    generateThumbnails(index(0,0), rowCount());
}
